-- eeprom 模型
-- 支持offsetwidth: 1, 2, 4
-- 数据大小：任意
-- 支持生成指定大小的数据文件，默认size为1024
local Eeprom = {
    offset_width = 1,
    size = 1024
}

local log = require "log"
local cjson = require "cjson"
local CommonI2c = require "protocol.CommonI2c"
local BinParser = require "data.BinParser"

function Eeprom:new(o, offset_width, size)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    self.offset_width = offset_width
    self.size = size
    return o
end

local EepromParser = {
    prot_parser = {},
    data_parser = {},
}

function EepromParser:new(o, prot_parser, data_parser)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    self.prot_parser = prot_parser
    self.data_parser = data_parser
    return o
end

function EepromParser:read_data(length)
    local offset = self.prot_parser:parse_offset()
    log:print(LOG_DEBUG, "read eeprom offset is %d, length: %d", offset, length)
    return self.data_parser:read_data(offset, length)
end

function EepromParser:write_data()
    local offset = self.prot_parser:parse_offset()
    local data = self.prot_parser:parse_data()
    log:print(LOG_DEBUG, "eeprom write_data offset: %d, data: %s", offset, cjson.encode(data))

    self.data_parser:write_data(offset, data)
end

function Eeprom:read(tx_buffer, length, filename)
    if type(tx_buffer) ~= "table" or #tx_buffer < 2 then    -- 2: 读命令时传输数据的最小长度
        log:print(LOG_ERROR, "tx_buffer length(%d) error", #tx_buffer)
        return
    end

    log:print(LOG_DEBUG, "read eeprom tx_buffer is %s, len: %d, size: %d", cjson.encode(tx_buffer), length, self.size)
    local common_i2c = CommonI2c:new(nil, tx_buffer, self.offset_width)
    local bin_parser = BinParser:new(nil, filename, self.size)

    local eeprom_parser = EepromParser:new(nil, common_i2c, bin_parser)
    return eeprom_parser:read_data(length)
end

function Eeprom:write(tx_buffer, filename)
    if type(tx_buffer) ~= "table" or #tx_buffer < 3 then    -- 3: 写命令时传输数据的最小长度
        log:print(LOG_ERROR, "tx_buffer length(%d) error", #tx_buffer)
        return
    end

    log:print(LOG_DEBUG, "write eeprom tx_buffer is %s", cjson.encode(tx_buffer))
    local common_i2c = CommonI2c:new(nil, tx_buffer, self.offset_width)
    local bin_parser = BinParser:new(nil, filename, self.size)

    local eeprom_parser = EepromParser:new(nil, common_i2c, bin_parser)
    eeprom_parser:write_data()
end

return Eeprom
